package com.team12.hotel404.controller.user;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.team12.hotel404.domain.Order;
import com.team12.hotel404.domain.User;
import com.team12.hotel404.service.OrderService;
import com.team12.hotel404.service.RoomService;
import com.team12.hotel404.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping(value = "/user")
@SessionAttributes("person")
public class UserController {

    /**@author:王畅
     * 设置阿里云短信验证ascClient的参数
     */
    private static final String product="Dysmsapi";
    private static final String domain="dysmsapi.aliyuncs.com";
    private static final String accessKeyId="LTAIlKSMFUjcQR4R";
    private static final String getAccessKeySecret="Fz5sbSZe7MPFmn0YNwLSFgdNFLwQUo";

    @Autowired
    private RoomService roomService;
    @Autowired
    private UserService userService;

    @Autowired
    OrderService orderService;

    @Autowired
    HttpServletRequest httpServletRequest;

    /**
     * 列出所有的用户
     * @param model
     * @return 返回所有的用户
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list_all_user(Model model){
        List<User> users = userService.listAllUser();
        model.addAttribute("users",users);
        return "admin/user-list";
    }

    /**
     *通过id找出用户信息
     * @param id
     * @return 返回一个用户信息
     */
    @RequestMapping(value = "/findById")
    public String find_user_by_id(Integer id,Model model){
        User user= userService.findById(id);
        model.addAttribute("user",user);
        return "admin/user-update";
    }

    /**
     * 更新用户信息
     * @param user
     * @return 跳转到用户列表
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public String update(User user){
        userService.updateHotelInfo(user);
        return "redirect:/user/list";
    }

    /**
     * 插入用户
     * @return 跳转到插入页面
     */
    @RequestMapping(value = "/insert",method = RequestMethod.GET)
    public String insert_user(){
        return "admin/user-insert";
    }

    /**
     * 插入用户
     * @param user
     * @return 跳转到用户列表
     */
    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    public String insert_user(User user){
        userService.insertUser(user);
        return "redirect:/user/list";
    }

    /**
     * 删除用户
     * @return 跳转到用户列表
     */
    @RequestMapping("/del")
    public String del_user(Integer id){
        userService.deleteUserById(id);
        return "redirect:/user/list";
    }

    /**
     * 用户名密码登录
     * @author:王畅
     * @return:登录
     */
    @RequestMapping(value = "/welcome",method = RequestMethod.POST)
    @ResponseBody
    public String user_login(@RequestParam("userName")String user_name,
                             @RequestParam("userPassword")String user_password,
                             Model model,
                             HttpSession session){

        User user = new User();
        user.setUserName(user_name);
        user.setUserPassword(user_password);
        User user1 = userService.find(user.getUserName());

        session.setAttribute("user",user1);
        session.setAttribute("current_userid",user1.getUserId());

        if (user1 != null) {
            if (user1.getUserPassword().equals(user.getUserPassword())) {
                user1.setUserStatus(1);
               // userService.updataStatus(user1);
                model.addAttribute("person",user1);
                session.setAttribute("user",user1);
                session.setAttribute("userId",user1.getUserId());
                return "true";
            }
        }
        return "false";
    }

    /**
     * 获取短信验证码
     * @author 王畅
     * @param telephone
     * @param model
     * @param session
     * @return
     * @throws ClientException
     */
    @PostMapping( value = "/getCode")
    @ResponseBody
    public String getCode(@RequestParam("user_phone")String telephone,
                          Model model,HttpSession session) throws ClientException {
        Random random=new Random();
        int randomInt=random.nextInt(99999);
        randomInt+=100000;
        String optCode=String.valueOf(randomInt);
        //将opt验证码同对应用户的手机号关联,使用httpsession
        httpServletRequest.getSession().setAttribute(telephone,optCode);
        session.setAttribute("sysCode",optCode);
        String inSessionOptCode=(String) this.httpServletRequest.getSession().getAttribute(telephone);
        //将opt验证码通过短信验证发送给用户
        System.setProperty("sun.net.client.defaultConnectTimeout", "1000");
        System.setProperty("sun.net.client.defaultReadTimeout", "1000");
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",accessKeyId ,getAccessKeySecret );
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        /* 必填:待发送手机号 */
        request.setPhoneNumbers(telephone);
        /* 必填:短信签名-可在短信控制台中找到 */
        request.setSignName("Hotel404"); //TODO: 这里是你短信签名
        /* 必填:短信模板code-可在短信控制台中找到 */
        request.setTemplateCode("SMS_171858988"); //TODO: 这里是你的模板code
        /* 可选:模板中的变量替换JSON串,如模板内容为"亲爱的用户,您的验证码为${code}"时,此处的值为 */
        request.setTemplateParam("{\"code\":\"" + optCode +"\"}");


        User  user = userService.findByPhone(telephone);
        if (user!=null){
            // hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if(sendSmsResponse.getCode()!= null && sendSmsResponse.getCode().equals("OK")){
                System.out.println("短信发送成功！验证码：" + optCode);
                return "ok";
            }else {
                System.out.println("短信发送失败！");
                return "failed";
            }
        }else{
            return "error";
        }
    }

    /**
     * 点击登陆，验证用户输入验证码的正确性
     *  @Author 王畅
     * @param userCode
     * @param telephone
     * @param session
     * @return
     */
    @RequestMapping("/checkCode")
    @ResponseBody
    public String checkCode(@RequestParam("inputCode")String userCode,Model model,
                            @RequestParam("user_phone")String telephone,HttpSession session){
        User  user = userService.findByPhone(telephone);
        String sysCode=session.getAttribute("sysCode").toString();
        if (userCode.equals(sysCode)){
            user.setUserStatus(1);
            model.addAttribute("person",user);
            session.setAttribute("userId",user.getUserId());
            return "true";
        }else{
            return "false";
        }
    }

    /**
     * 用户退出系统
     * @author：王畅
     * @return：返回到主页登录前界面
     */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String user_logout(SessionStatus sessionStatus,HttpSession session){
        session.invalidate();
        sessionStatus.setComplete();
        return "redirect:/pages/toHotel";
    }


    /**
     * @author:王畅
     * @return:注册
     */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
//    public String user_regist(@RequestParam("userId")Integer id,@RequestParam("userName")String name,@RequestParam("userPassword")String pwd,
//                              @RequestParam("userPhone")String phone,@RequestParam("userEmail")String email,

//            return "/ser/newRegist";
//        }else {
//            return "ser/hotelIndex";
//        }
//    }
        /**
         * 另一种方法⬆
         * */

    public String user_regist(User user){
        int u = userService.Regist(user);
        if (u==0){
            return "/user/newRegist";
        }else {
            return "/user/hotelIndex";
        }
    }



    /**
     * @author:王畅
     * @return:各页面跳转
     */

    @RequestMapping("/toOrders")
    public String toOrders(Model model){
        model.addAttribute("orders",orderService.findAll());
        return "/user/showAllOrders";
    }

    @RequestMapping("/check")
    public String check(@RequestParam("check") Integer id,Model model){
        model.addAttribute("orders",orderService.search(id));
        return "/user/showAllOrders";
    }

    @RequestMapping("/userCenterIndex")
    public String toUser(){

        return "/user/userCenterIndex";

    }

    @RequestMapping("/userCenter")
    public String toUserCenter(HttpSession session,Model model){
        User user1 = (User) session.getAttribute("user");
        if(user1==null){
            return null;
        }else{
            Integer id = user1.getUserId();
            User user = userService.findById(id);
            model.addAttribute("user",user);
            return  "/user/userCenter";
        }
    }

    @RequestMapping("/toOrderCheck")
    public String toUserCheck(HttpSession session ,Model model) {
//        Integer uid = 1;
        User user1 = (User) session.getAttribute("user");
        Integer uid = user1.getUserId();
        User user = userService.findById(uid);
        model.addAttribute("order", orderService.searchOne(uid));
        return "/user/showOneOrder";
    }

    @RequestMapping("/toUMChange")
    public String toUMessageChange(HttpSession session,Model model){
//        Integer uid = 1;
        User user1 = (User) session.getAttribute("user");
        Integer uid = user1.getUserId();

        User user = userService.findById(uid);
        model.addAttribute("user",user);

        return "/user/toUserMessageChange";
    }

    @RequestMapping(value = "UpdateUser",method = RequestMethod.POST)
    public String toUpdateUser(User user){
        userService.updateUserInfo(user);
        return "redirect:/user/userCenter";
    }
    
    @RequestMapping(value = "/toGallery")
    public String to_gallery(){
        return "/user/gallery";
    }

    @RequestMapping(value = "/toRooms")
    public String to_rooms(){return "/user/rooms";}

    @RequestMapping(value = "/toCenter")
    public String to_center(){return "/user/userCenter";}

    @RequestMapping(value = "/toIndex")
    public String to_hotel(){return "redirect:/pages/toHotel";}

    @RequestMapping(value = "/test")
    public String test(Model model,Integer id){
        Integer sid= 1;
        List<Order> orders = orderService.OrderDetails(sid);
//        for (Order order:orders) {
//            order.
//
//        }

        System.out.println(orders.size());
        model.addAttribute("orders",orders);
        return "User/test";
    }


}
